
(function (sauberfant) {

	var cookie = {
		set: function (name, value, days) {
			var expires = "";
			if (days) {
				var date = new Date();
				date.setTime(date.getTime() + (days*24*60*60*1000));
				var expires = "; expires=" + date.toGMTString();
			}

			document.cookie = name + "=" + value + expires + "; path=/";
		},

		get: function (name) {

			var cookie = document.cookie.split(name+"=");

			if (cookie.length-1) {
				return cookie[1].split(";")[0];
			}

			return null;
		},

		delete: function (name) {
			cookie.create(name, "", -1);
		}
	};


	var get_cookie_name = function (page_id) {
		return sauberfant.options.cookie.name + '_' + page_id;
	}


	// 123456|1234567890|1234567890|1234567890|1234567890|1234567890|7
	// user_id|page_id|first_visit|last_visit|this_visit|last_hit|visit_count
	var decode = function (cookie_string) {

		if (typeof cookie_string === 'string' && cookie_string.match(/([0-9]+\|){6}([0-9]+)/)) {
			var tokens = cookie_string.split('|');
			if (tokens.length === 7) {
				return {
					user:			parseInt(tokens[0], 10),
					page:			parseInt(tokens[1], 10),
					first:			parseInt(tokens[2], 10),
					last:			parseInt(tokens[3], 10),
					current:		parseInt(tokens[4], 10),
					hit:			parseInt(tokens[5], 10),
					count: 			parseInt(tokens[6], 10)
				};
			}
		}
		return false;
	}


	var encode = function (c) {
		return [c.user, c.page, c.first, c.last, c.current, c.hit, c.count].join('|');
	}




	sauberfant.identify = function (page_id, user_id) {

		if (!page_id) {
			return false;
		}

		var name	= get_cookie_name(page_id)
		,	c 		= decode(cookie.get(name))
		,	now 	= Math.round(new Date().getTime()/1000);

		if (!user_id) {
			if (c.user) {
				user_id = c.user;
			} else {
				user_id = sauberfant.options.cookie.random_user_id;
			}
		}

		if (c && c.user === user_id) {

			c.hit = now;

			if (now - sauberfant.options.cookie.session_length > c.current) {
				c.last 		= c.current;
				c.current 	= now;
				c.count++;
			}

		} else {

			c = {
				page: 		page_id,
				user: 		user_id,
				first: 		now,
				last: 		now,
				current: 	now,
				hit: 		now,
				count: 		1
			}
		}

		cookie.set(name, encode(c), sauberfant.options.cookie.cookie_lifetime);

		return c;
	}

	sauberfant.get_cookie = function (page_id) {
		return cookie.get(get_cookie_name(page_id));
	}



})(sauberfant);





